package com.uuuo.rxjava1;

import org.junit.Test;

import rx.functions.Action1;
import rx.subjects.AsyncSubject;
import rx.subjects.BehaviorSubject;
import rx.subjects.PublishSubject;
import rx.subjects.ReplaySubject;

/**
 * Created by JiaTao on 2017/4/6.
 */

public class G_Subject extends A_Base {
//    值得注意的是一定要用Subcect.create()的方式创建并使用，不要用just(T)、from(T)、create(T)创建，否则会导致失效...


    //简单的说使用AsyncSubject无论输入多少参数，永远只输出最后一个参数。
    @Test
    public void AsyncSubjectDemo() {
        AsyncSubject<Integer> asyncSubject = AsyncSubject.create();
        asyncSubject.onNext(1);
        asyncSubject.onNext(2);
        asyncSubject.onNext(3);
        asyncSubject.onCompleted();
        asyncSubject.subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                showMsg(integer + "");
            }
        });
    }

    @Test
    public void BehaviorSubjectDemo() {
        BehaviorSubject<Integer> behaviorSubject = BehaviorSubject.create();
        behaviorSubject.onNext(1);

        behaviorSubject.onNext(2);
        behaviorSubject.subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                showMsg(integer + "");
            }
        });
        behaviorSubject.onNext(3);
        behaviorSubject.onCompleted();
        behaviorSubject.subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                showMsg(integer + "");
            }
        });
    }

    @Test
    public void PublishSubjectDemo() {
        PublishSubject bs = PublishSubject.create();
        // 这里订阅接收1， 2， 3
        bs.onNext(1);
        // 这里订阅接收2， 3

        bs.subscribe(
                new Action1<Integer>() {
                    @Override
                    public void call(Integer o) {
                        showMsg(o + "");
                    }
                });


        bs.onNext(2);
        // 这里订阅接收3
        bs.onNext(3);
//        bs.onCompleted();
        // 这里订阅无接收


    }

    @Test
    public void ReplaySubjectDemo() {
        ReplaySubject bs = ReplaySubject.create();
// 无论何时订阅都会收到1，2，3
        bs.onNext(1);
        bs.subscribe(
                new Action1<Integer>() {
                    @Override
                    public void call(Integer o) {
                        showMsg(o + "----");
                    }
                });
        bs.onNext(2);
        bs.onNext(3);
        bs.onCompleted();
        bs.subscribe(
                new Action1<Integer>() {
                    @Override
                    public void call(Integer o) {
                        showMsg(o + "");
                    }
                });
    }
}
